import { _decorator, Node, instantiate } from 'cc'
import Singleton from '../Base/Singleton'
import { EntityTypeEnum } from '../Common'
import DataManager from './DataManager'

// 实体对象池管理---（复用对象）
export class ObjectPoolManager extends Singleton {
  static get Instance() {
    return super.GetInstance<ObjectPoolManager>()
  }
  /**
  stage
    objectPool
        bulletPool
            bullet1
            bullet2
        explosionPool
            explosoin1
            explosoin2
*/
  // 对象池节点
  private objectPool: Node
  // 实体类型 备用节点组集合（使用时取出用完放回去）
  private map: Map<EntityTypeEnum, Node[]> = new Map()

  // 获取对象
  get(type: EntityTypeEnum) {
    if (!this.objectPool) {
      // 初始化对象池挂载到舞台
      this.objectPool = new Node('ObjectPool')
      this.objectPool.setParent(DataManager.Instance.stage)
    }

    if (!this.map.has(type)) {
      // 实体类挂载到对象池
      this.map.set(type, [])
      const container = new Node(type + 'Pool')
      container.setParent(this.objectPool)
    }

    const nodes = this.map.get(type)
    if (!nodes.length) {
      // 实体挂载到对应类
      const prefab = DataManager.Instance.prefabMap.get(type)
      const node = instantiate(prefab)
      node.name = type
      node.setParent(this.objectPool.getChildByName(type + 'Pool'))
      node.active = true
      return node
    } else {
      const node = nodes.pop()
      node.active = true
      return node
    }
  }
  // 归还对象
  ret(node: Node) {
    node.active = false
    this.map.get(node.name as EntityTypeEnum).push(node)
  }

  // 清空对象池（如果未清空第二次游戏时会冲突）
  reset() {
    this.objectPool = null
    this.map.clear()
  }
}
